# from matplotlib import pyplot
import createAlphabet as ab
from pydub import AudioSegment
from pydub.silence import split_on_silence
import os

# 初始化
audio_path = "audio/pali_vowel.wav"
# aduio_out_Path = "./audio_out/"
audio_type = 'wav'

# 读入音频
print('读入音频')
sound = AudioSegment.from_file(audio_path, format=audio_type)
# sound = sound[:3 * 60 * 1000]  # 如果文件较大，先取前3分钟测试，根据测试结果，调整参数

# 分割
print('开始分割')
chunks = split_on_silence(sound, min_silence_len=120,
                          silence_thresh=-70)  # min_silence_len: 拆分语句时，静默满0.1秒则拆分。silence_thresh：小于-70dBFS以下的为静默。
lenck = len(chunks)


# 音节表导入
myalphabet = ab.allVowels
lenab = len(myalphabet)



# 创建保存目录
file_path = os.path.split(audio_path)[0]
chunks_path = file_path + '/chunks/'
if not os.path.exists(chunks_path):
    os.mkdir(chunks_path)

# 保存所有分段
print('开始保存')

for i in range(len(chunks)):
    new = chunks[i]
    if myalphabet[i]:
        save_name = chunks_path + '%s.%s' % (myalphabet[i], audio_type)
    else:
        save_name = chunks_path + '%04d.%s' % (i, audio_type)
    new.export(save_name, format=audio_type)
    print(save_name, len(new))

print('保存完毕')
print('共自动生成：%d个音节' % lenab)
print('一共分割为：%d个读音片段' % lenck)
